﻿//==============================================================================
// File: GroupingItemsControlRegionAdapter.cs
// Created: 2008-04-30
// Author: Piotr Włodek
//==============================================================================
// This file is a part of MAMMOTH project.
// Copyright (C) 2010 AGH University of Science and Technology, Krakow.
// https://caribou.iisg.agh.edu.pl/trac/mammoth
//
// Mammoth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Mammoth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with Mammoth. If not, see http://www.gnu.org/licenses/.
//==============================================================================

using System;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using WpfRcp.Core.Common;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Composite.Presentation.Regions;
using System.Collections.Generic;
using WpfRcp.Core.Common.Extensions;
using System.Windows;
using WpfRcp.Services.Commands;

namespace WpfRcp.Helpers.CompositePresentation
{
    public class GroupingItemsControlRegionAdapter : RegionAdapterBase<ItemsControl>
    {
        public GroupingItemsControlRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
            : base(regionBehaviorFactory)
        {
        }

        protected override void Adapt(IRegion region, ItemsControl regionTarget)
        {
            if (regionTarget.ItemsSource != null || (BindingOperations.GetBinding(regionTarget, ItemsControl.ItemsSourceProperty) != null))
                throw new InvalidOperationException();

            // If control has child items, move them to the region and then bind
            // control to region. Can't set ItemsSource if child items exist.
            if (regionTarget.Items.Count > 0)
            {
                foreach (object childItem in regionTarget.Items)
                {
                    region.Add(childItem);
                }

                // Control must be empty before setting ItemsSource.
                regionTarget.Items.Clear();
            }

            regionTarget.ItemsSource = new GroupingViewsCollection(region.Views, typeof(Separator));
        }

        protected override IRegion CreateRegion()
        {
            return new AllActiveRegion();
        }
    }
}